package com.zmn.oms.dubbo.impl.saas;

import com.google.common.collect.Lists;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.dms.common.enums.DiscountTypeEnums;
import com.zmn.oms.business.interfaces.apply.CancelApplyBService;
import com.zmn.oms.business.interfaces.orderamount.OrderDiscountCalcBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.business.interfaces.worktrack.WorkTrackBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderPayConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.OrderVisitStatusConsts;
import com.zmn.oms.common.dro.normal.pay.AmountDRO;
import com.zmn.oms.common.utils.TimeTextUtil;
import com.zmn.oms.dubbo.dto.common.work.OrderDetailDiscountDRO;
import com.zmn.oms.dubbo.dto.common.work.OrderDetailTagDRO;
import com.zmn.oms.dubbo.dto.saas.OrderFinalPriceQuotationDRO;
import com.zmn.oms.dubbo.dto.saas.SaasOrderDetailDRO;
import com.zmn.oms.dubbo.dto.zmn.order.OrderProductDRO;
import com.zmn.oms.dubbo.dto.zmn.serviceitem.OrderServiceItemDRO;
import com.zmn.oms.dubbo.interfaces.saas.SaasOrderWorkListRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.bo.work.apply.cancel.CancelApplyResultBO;
import com.zmn.oms.model.entity.acceptance.OrderWorkAcceptance;
import com.zmn.oms.model.entity.acceptance.OrderWorkAcceptanceDbQuery;
import com.zmn.oms.model.entity.changerecord.OrderChangeRecord;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.omstrack.OrderWorkTrack;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.orderfinalpricequotation.OrderFinalPriceQuotation;
import com.zmn.oms.model.entity.orderfinalpricequotation.OrderFinalPriceQuotationQuery;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.quotation3.OrderFaultPhenomenon;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.tag.OrderTag;
import com.zmn.oms.model.entity.visit.OrderVisit;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.work.modify.amount.ZsServiceItemVO;
import com.zmn.oms.services.interfaces.acceptance.OrderWorkAcceptanceService;
import com.zmn.oms.services.interfaces.changerecord.OrderChangeRecordService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.orderfinalpricequotation.OrderFinalPriceQuotationService;
import com.zmn.oms.services.interfaces.pay.OrderPayService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.quotation3.OrderFaultPhenomenonService;
import com.zmn.oms.services.interfaces.tag.OrderTagService;
import com.zmn.oms.services.interfaces.visit.OrderVisitService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.services.interfaces.worktrack.WorkTrackService;
import com.zmn.oms.zmn.business.interfaces.discount.ZsOrderDiscountBService;
import com.zmn.oms.zmn.normal.business.interfaces.serviceitem.ZsNormalOrderServiceItemBService;
import com.zmn.pay.common.constant.PayConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.apache.hbase.thirdparty.com.google.common.collect.Streams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 类描述：saas订单查询
 *
 * @author heciqi
 * @date 2021/7/13 11:13
 */
@Slf4j
@Service(loadbalance = "roundrobin", timeout = 10000, retries = 0, version = DubboConsts.INTERFACE_VERSION, validation = "true")
public class SaasOrderWorkListRemoteServiceImpl implements SaasOrderWorkListRemoteService {
	@Autowired
	private OrderWorkService orderWorkService;
	@Autowired
	private OrderProductService orderProductService;
	@Autowired
	private OrderDetailService orderDetailService;
	@Autowired
	protected OrderMasterService orderMasterService;
	@Autowired
	protected OrderExtendService orderExtendService;
	@Autowired
	OrderWorkListBService orderWorkListBService;
	@Autowired
	OrderDiscountCalcBService orderDiscountCalcBService;
	@Autowired
	OrderChangeRecordService orderChangeRecordService;
	@Autowired
	WorkTrackService workTrackService;
	@Autowired
	OrderPayService orderPayService;
	@Autowired
	WorkTrackBService workTrackBService;
	@Autowired
	ZsOrderDiscountBService zsOrderDiscountBService;
	@Autowired
	protected ZsNormalOrderServiceItemBService zsNormalOrderServiceItemBService;
	@Autowired
	protected OrderTagService orderTagService;
	@Autowired
	protected OrderVisitService orderVisitService;
	@Autowired
	private OrderWorkAcceptanceService orderWorkAcceptanceService;
	@Autowired
	private CancelApplyBService cancelApplyBService;

	@Resource
	private OrderFinalPriceQuotationService orderFinalPriceQuotationService;

	@Resource
	private OrderFaultPhenomenonService orderFaultPhenomenonService;

	/**
	 * 根据订单id和工单id查询工单详情
	 *
	 * @param orderId
	 * @param workId
	 * @return
	 */
	@Override
	public ResponseDTO<SaasOrderDetailDRO> getOrderDetailById(@NotNull(message = "入参不能为空") Long orderId,
															  @NotNull(message = "入参不能为空") Long workId) {

		log.debug("详情查询SaasOrderWorkListRemoteServiceImpl#getOrderDetailById 入参：{},{}",orderId,workId);
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
		if (Objects.isNull(orderWork)) {
			return ResponseDTO.fail("订单不存在");
		}

		SaasOrderDetailDRO saasOrderDetailDRO = new SaasOrderDetailDRO();
		// 工单
		this.orderWorkSet(saasOrderDetailDRO, orderWork);
		// 进度款
		this.amountListSet(saasOrderDetailDRO, orderWork);
		// 用户
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKeySrcMaster(orderId);
		this.orderDetailSet(saasOrderDetailDRO, orderDetail);
		// 退款
		this.refundSet(saasOrderDetailDRO, orderWork);
		// 产品
		List<OrderProduct> orderProductList = orderProductService.listOrderProductByOrderIdSrcMaster(orderId);
		saasOrderDetailDRO.setOrderProductList(BeanMapper.mapList(orderProductList, OrderProductDRO.class));
		// 服务项
		saasOrderDetailDRO.setOrderServiceItemList(this.listServiceItem(orderId));
		// 优惠
		saasOrderDetailDRO.setOrderDiscountList(this.listDiscount(orderId));
		// 标签
		saasOrderDetailDRO.setTags(this.listTag(orderId, workId));
        // 支付优惠金额
        saasOrderDetailDRO.setPayDiscountAmount(orderWork.getPayDiscountAmount());

		// 一口价报价信息
		if (Objects.equals(orderWork.getFinalPrice(), com.zmn.consts.GlobalConsts.YES) ||
				Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_FINAL_PRICE)){
			List<OrderFinalPriceQuotation> orderFinalPriceQuotations = orderFinalPriceQuotationService.
					listByQuery(OrderFinalPriceQuotationQuery.builder().orderId(orderId).workId(workId).build());
			if (CollectionUtil.isNotNullOrEmpty(orderFinalPriceQuotations)){
				OrderFinalPriceQuotationDRO orderFinalPriceQuotationDRO = new OrderFinalPriceQuotationDRO();
				OrderFinalPriceQuotation orderFinalPriceQuotation = orderFinalPriceQuotations.get(0);
				OrderProduct orderProduct = orderProductList.get(0);
				// 产品名称
				orderFinalPriceQuotationDRO.setProductId(orderWork.getProductId());
				orderFinalPriceQuotationDRO.setProductName(orderProduct.getProductName());
				if (!Objects.equals(orderFinalPriceQuotation.getProductId(),orderWork.getProductId())) {
					orderFinalPriceQuotationDRO.setOldProductId(orderFinalPriceQuotation.getProductId());
					orderFinalPriceQuotationDRO.setOldProductName(orderFinalPriceQuotation.getProductName());
				}
				// 品牌名称
				orderFinalPriceQuotationDRO.setBrandId(orderProduct.getBrandId());
				orderFinalPriceQuotationDRO.setBrandName(orderProduct.getBrandName());
				if (!Objects.equals(orderFinalPriceQuotation.getBrandId(),orderProduct.getBrandId())) {
					orderFinalPriceQuotationDRO.setOldBrandId(orderFinalPriceQuotation.getBrandId());
					orderFinalPriceQuotationDRO.setOldBrandName(orderFinalPriceQuotation.getBrandName());
				}
                // 价格
				orderFinalPriceQuotationDRO.setTotalAmount(orderWork.getTotalAmount());
				if (!Objects.equals(orderFinalPriceQuotation.getTotalAmount(),orderWork.getTotalAmount())) {
					orderFinalPriceQuotationDRO.setOldTotalAmount(orderFinalPriceQuotation.getTotalAmount());
				}

				// 故障现象
				List<OrderFaultPhenomenon> orderFaultPhenomena = orderFaultPhenomenonService.listByOrderId(orderId);
				if (CollectionUtil.isNotNullOrEmpty(orderFaultPhenomena)){
					OrderFaultPhenomenon orderFaultPhenomenon = orderFaultPhenomena.get(0);
					orderFinalPriceQuotationDRO.setPhenId(orderFaultPhenomenon.getPhenId());
					orderFinalPriceQuotationDRO.setPhenName(orderFaultPhenomenon.getPhenName());
					if (!Objects.equals(orderFinalPriceQuotation.getPhenId(),orderFaultPhenomenon.getPhenId())){
						orderFinalPriceQuotationDRO.setOldPhenId(orderFinalPriceQuotation.getPhenId());
						orderFinalPriceQuotationDRO.setOldPhenName(orderFinalPriceQuotation.getPhenName());
					}
				}else {
					orderFinalPriceQuotationDRO.setPhenId(orderFinalPriceQuotation.getPhenId());
					orderFinalPriceQuotationDRO.setPhenName(orderFinalPriceQuotation.getPhenName());
				}

				// 服务项目
				List<OrderServiceItemDRO> orderServiceItemList = saasOrderDetailDRO.getOrderServiceItemList();
				if(CollectionUtil.isNotNullOrEmpty(orderServiceItemList)){
					OrderServiceItemDRO orderServiceItemDRO = orderServiceItemList.get(0);
					orderFinalPriceQuotationDRO.setServItemName(orderServiceItemDRO.getServItemName());
					orderFinalPriceQuotationDRO.setServItemId(orderServiceItemDRO.getServItemId());
					orderFinalPriceQuotationDRO.setItemPrice(orderServiceItemDRO.getItemPrice());
					if (!Objects.equals(orderServiceItemDRO.getServItemId(),orderFinalPriceQuotation.getServItemId())){
						orderFinalPriceQuotationDRO.setOldServItemName(orderFinalPriceQuotation.getServItemName());
						orderFinalPriceQuotationDRO.setOldServItemId(orderFinalPriceQuotation.getServItemId());
						orderFinalPriceQuotationDRO.setOldItemPrice(orderFinalPriceQuotation.getItemPrice());
					}
				}

				saasOrderDetailDRO.setOrderFinalPriceQuotationDRO(orderFinalPriceQuotationDRO);
			}
		}
		log.debug("详情查询SaasOrderWorkListRemoteServiceImpl#getOrderDetailById 出参：{}",saasOrderDetailDRO);
		return ResponseDTO.success(saasOrderDetailDRO);
	}

	private List<OrderDetailDiscountDRO> listDiscount(Long orderId) {
		// 订单优惠明细
		List<OrderDiscount> discountList = zsOrderDiscountBService.listByOrderId(orderId);
		List<OrderDetailDiscountDRO> orderDetailDiscountList = BeanMapper.mapList(discountList, OrderDetailDiscountDRO.class);
		if (CollectionUtil.isNotNullOrEmpty(orderDetailDiscountList)) {
			orderDetailDiscountList.forEach(e -> {
				e.setCategName(StringUtils.defaultString(DiscountTypeEnums.getSubName(e.getCateg())));
				if (Objects.equals(e.getCateg(), DiscountTypeEnums.DISCOUNT_COUP_ONCECARD.getSubType())) {
					e.setCategName("权益卡");
				}
			});

			// // 优惠券 使用的优惠券、现金券、代金券换
			// Integer discountCoupon = orderDetailDiscountList.stream().filter(e -> e.getCateg() != null && e.getAmount() != null && Lists.newArrayList(31, 32, 33).contains(e.getCateg())).mapToInt(e -> e.getAmount()).sum();
			// weixinOrderDetail.setDiscountCoupon(discountCoupon);
			// // 其他优惠
			// Integer otherDiscount = orderDetailDiscountList.stream().filter(e -> e.getCateg() != null && e.getAmount() != null && !Lists.newArrayList(11, 21, 31, 32, 33).contains(e.getCateg())).mapToInt(e -> e.getAmount()).sum();
			// weixinOrderDetail.setOtherDiscount(otherDiscount);
		}
		return orderDetailDiscountList;
	}

	private List<OrderDetailTagDRO> listTag(Long orderId, Long workId) {
		// 订单优惠明细
		List<OrderTag> tags = orderTagService.listOrderTagByOrderId(orderId, workId);
		return BeanMapper.mapList(tags, OrderDetailTagDRO.class);
	}

	private List<OrderServiceItemDRO> listServiceItem(Long orderId) {
		List<ZsServiceItemVO> serviceItemVos = null;
		try {
			serviceItemVos = zsNormalOrderServiceItemBService.findServiceItemVo(orderId, orderId);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		if (CollectionUtil.isNullOrEmpty(serviceItemVos)) {
			return Collections.emptyList();
		}
		// 服务项信息
		List<OrderServiceItem> orderServiceItems = new LinkedList<>();
		for (ZsServiceItemVO obj : serviceItemVos) {
			if (!org.apache.commons.collections4.CollectionUtils.isEmpty(obj.getServiceItemList())) {
				orderServiceItems.addAll(obj.getServiceItemList());
			}
		}
		List<OrderServiceItemDRO> orerServiceItemDRO = BeanMapper.mapList(orderServiceItems, OrderServiceItemDRO.class);
		return orerServiceItemDRO;
	}

	// 处理金额
	private void amountListSet(SaasOrderDetailDRO saasOrderDetailDRO, OrderWork orderWork) {
		// 查询上门记录
		List<OrderVisit> orderVisitList = orderVisitService.listByOrderIdSrcMaster(orderWork.getOrderId());
		if (CollectionUtil.isNullOrEmpty(orderVisitList)) {
			OrderWorkAcceptanceDbQuery query = new OrderWorkAcceptanceDbQuery();
			query.setOrderId(orderWork.getOrderId());
			List<OrderWorkAcceptance> acceptanceList = orderWorkAcceptanceService.listOrderWorkAcceptanceByQuerySrcMaster(query);
			if (CollectionUtil.isNotNullOrEmpty(acceptanceList)) {
				// 兼容性处理
				List<AmountDRO> amountDROList = Lists.newArrayListWithCapacity(2);
				OrderWorkAcceptance deposit = acceptanceList.stream()
						.filter(item -> Objects.equals(item.getAcceptanceType(), OrderConsts.ORDER_ACCEPTANCE_TYPE_DEPOSIT))
						.findFirst().orElse(null);
				if (Objects.nonNull(deposit)) {
					AmountDRO dro = new AmountDRO();
					dro.setAcceptanceId(deposit.getAcceptanceId());
					dro.setAmount(Optional.ofNullable(orderWork.getDepositAmount()).orElse(0));
					dro.setAmountType(OrderPayConsts.ORDER_PAY_DEPOSIT);
					dro.setPayStatus(orderWork.getDepositStatus());
					amountDROList.add(dro);
				}

				OrderWorkAcceptance payment = acceptanceList.stream()
						.filter(item -> Objects.equals(item.getAcceptanceType(), OrderConsts.ORDER_ACCEPTANCE_TYPE_PAYMENT))
						.findFirst().orElse(null);
				if (Objects.nonNull(payment)) {
					AmountDRO dro = new AmountDRO();
					dro.setAcceptanceId(payment.getAcceptanceId());
					dro.setAmount(Optional.ofNullable(orderWork.getMasterAmount()).orElse(0));
					dro.setAmountType(OrderPayConsts.ORDER_PAY_MASTER);
					dro.setPayStatus(orderWork.getMasterPayStatus());
					amountDROList.add(dro);
				}
				saasOrderDetailDRO.setAmountList(amountDROList);
			}
			return;
		}

		List<AmountDRO> amountDROList = Lists.newArrayListWithCapacity(orderVisitList.size());

		orderVisitList.forEach(orderVisit -> {
			// 过滤已取消的上门
			if (Objects.equals(orderVisit.getVisitStatus(), OrderVisitStatusConsts.ORDER_VISIT_STATUS_CANCEL)) {
				if (Objects.equals(orderVisit.getPayStatus(), PayConsts.PAY_STATUS_NONE)) {
					return;
				}
			}

			AmountDRO dro = new AmountDRO();
			dro.setAcceptanceId(orderVisit.getAcceptanceId());
			dro.setVisitId(orderVisit.getVisitId());
			dro.setOrderPayId(orderVisit.getOrderPayId());
			dro.setAmount(orderVisit.getAmount());
			dro.setAmountType(orderVisit.getAmountType());
			if (NumberUtil.isNullOrZero(orderVisit.getOrderPayId()) && NumberUtil.isNullOrZero(orderVisit.getAcceptanceId())) {
				dro.setPayStatus(PayConsts.PAY_STATUS_DONE);
			} else {
				dro.setPayStatus(orderVisit.getPayStatus());
			}
			amountDROList.add(dro);
		});

		OrderWorkAcceptanceDbQuery query = new OrderWorkAcceptanceDbQuery();
		query.setOrderId(orderWork.getOrderId());
		List<OrderWorkAcceptance> acceptanceList = orderWorkAcceptanceService.listOrderWorkAcceptanceByQuerySrcMaster(query);
		if (CollectionUtil.isNotNullOrEmpty(acceptanceList)) {
			OrderWorkAcceptance acceptance = Streams.findLast(acceptanceList.stream()
					.filter(item -> Objects.equals(item.getAcceptanceType(), OrderConsts.ORDER_ACCEPTANCE_TYPE_PAYMENT)))
					.orElse(null);
			if (Objects.nonNull(acceptance)) {
				AmountDRO waitAmountDRO = Streams.findLast(amountDROList.stream()
						.filter(item -> Objects.equals(item.getPayStatus(), PayConsts.PAY_STATUS_NONE)))
						.orElse(null);
				int waitAmount = 0;
				if (Objects.nonNull(waitAmountDRO)) {
					waitAmount = waitAmountDRO.getAmount();
				}
				AmountDRO dro = new AmountDRO();
				dro.setAcceptanceId(acceptance.getAcceptanceId());
				dro.setAmount(Optional.ofNullable(orderWork.getMasterAmount()).orElse(0) - waitAmount);
				dro.setAmountType(OrderPayConsts.ORDER_PAY_MASTER);
				dro.setPayStatus(orderWork.getMasterPayStatus());
				amountDROList.add(dro);
			}
		}

		saasOrderDetailDRO.setAmountList(amountDROList);
	}

	private void orderWorkSet(SaasOrderDetailDRO saasOrderDetailDRO, OrderWork orderWork) {
		saasOrderDetailDRO.setCityId(orderWork.getCityId());
		saasOrderDetailDRO.setChannelId(orderWork.getChannelId());
		saasOrderDetailDRO.setOrderId(orderWork.getOrderId());
		saasOrderDetailDRO.setType(orderWork.getType());
		saasOrderDetailDRO.setBizType(orderWork.getBizType());
		saasOrderDetailDRO.setBizLine(orderWork.getBizLine());
		saasOrderDetailDRO.setWorkId(orderWork.getWorkId());
		saasOrderDetailDRO.setReworkId(orderWork.getReworkId());
		saasOrderDetailDRO.setUserId(orderWork.getUserId());
		int orderStatus = OrderStatusConsts.getOrderStatus(orderWork.getStatus(), orderWork.getResultStatus());
		saasOrderDetailDRO.setStatus(orderStatus);
		saasOrderDetailDRO.setStatusName(OrderStatusConsts.getOrderStatusName(orderStatus));
		saasOrderDetailDRO.setPayStatus(orderWork.getPayStatus());
		saasOrderDetailDRO.setPrepayStatus(orderWork.getPrepayStatus());
		saasOrderDetailDRO.setReceiveTime(orderWork.getReceiveTime());
		saasOrderDetailDRO.setDutyTime(orderWork.getDutyTime());
		// 预约时间文案说明
		if (orderWork.getDutyTime() != null) {
			saasOrderDetailDRO.setDutyTimeText(TimeTextUtil.getDutyText(orderWork.getDutyTime()));
		}
		saasOrderDetailDRO.setCompleteTime(orderWork.getCompleteTime());
		saasOrderDetailDRO.setDepositTime(orderWork.getDepositTime());
		saasOrderDetailDRO.setPayTime(orderWork.getPayTime());
		saasOrderDetailDRO.setCancelTime(orderWork.getCancelTime());
		saasOrderDetailDRO.setPrepayTime(orderWork.getPrepayTime());
		saasOrderDetailDRO.setOriginalAmount(orderWork.getOriginalAmount());
		saasOrderDetailDRO.setPrepayAmount(orderWork.getPrepayAmount());
		saasOrderDetailDRO.setDiscountAmount(orderWork.getDiscountAmount());
		saasOrderDetailDRO.setTotalAmount(orderWork.getTotalAmount());
		saasOrderDetailDRO.setFactAmount(this.factAmount(orderWork));
		saasOrderDetailDRO.setDepositAmount(this.getDepositAmount(orderWork));
		saasOrderDetailDRO.setWaitPayAmount(this.getWaitPayAmount(orderWork, saasOrderDetailDRO));
		saasOrderDetailDRO.setFinalPrice(orderWork.getFinalPrice());
		saasOrderDetailDRO.setServItemType(orderWork.getServItemType());
		saasOrderDetailDRO.setFullPaymentFlag(orderWork.getFullPaymentFlag());


		saasOrderDetailDRO.setMasterId(orderWork.getMasterId());
		saasOrderDetailDRO.setMasterName(orderWork.getMasterName());
		// 工单工程师
		List<OrderMaster> orderMasterList = orderMasterService.listMasterByOrderIdList(Lists.newArrayList(orderWork.getOrderId()));
		if (!CollectionUtils.isEmpty(orderMasterList)) {
			Optional<OrderMaster> orderMasterOptional = orderMasterList.stream().filter(e -> Objects.equals(e.getMasterId(), orderWork.getMasterId())).findFirst();
			if (orderMasterOptional.isPresent()) {
				saasOrderDetailDRO.setMasterPhone(orderMasterOptional.get().getMasterPhone());
			}
		}
		//师傅相片
		OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderWork.getOrderId());
		Integer threeDaysRefund = GlobalConsts.NO;
		if (Objects.nonNull(orderExtend)) {
			saasOrderDetailDRO.setMasterSrc(orderExtend.getMasterSrc());
			threeDaysRefund = Objects.equals(orderExtend.getAllowRefund(), GlobalConsts.YES) ? GlobalConsts.YES : GlobalConsts.NO;
		}
		saasOrderDetailDRO.setThreeDaysRefund(threeDaysRefund);// 是否为三日退订单
		saasOrderDetailDRO.setServCategId(orderWork.getServCategId());
		saasOrderDetailDRO.setShowCategId(orderWork.getShowCategId());
		saasOrderDetailDRO.setShowCategOneId(orderWork.getShowCategOneId());

		// 返修次数
		Integer reworkCount = orderWorkListBService.countReworkSuccessByWorkId(orderWork.getOrderId(), orderWork.getWorkId());
		saasOrderDetailDRO.setReworkThirdTime(reworkCount);
		saasOrderDetailDRO.setDiscountActivityId(orderWork.getDiscountActivityId());
		saasOrderDetailDRO.setLateAmount(orderDiscountCalcBService.getLateAmount(orderWork.getOrderId(), orderWork.getDiscountActivityId()));
		saasOrderDetailDRO.setServCategName("");
		// 派单标示（是否存在多次派单，派单撤回算多次）
		OrderChangeRecord changeRecord = orderChangeRecordService.getChangeRecordByOrderId(orderWork.getOrderId());
		if (Objects.nonNull(changeRecord)) {
			// 是否多次派单
			boolean isMultDistrbute = (changeRecord.getFirstDistributeTime() != null && NumberUtil.isNullOrZero(orderWork.getMasterId()))
					|| changeRecord.getDistributeCount() > 0;
			if (isMultDistrbute) {
				saasOrderDetailDRO.setMultipleDistribute(GlobalConsts.YES);
			} else {
				saasOrderDetailDRO.setMultipleDistribute(GlobalConsts.NO);
			}
		}

		// 取消申请
		CancelApplyResultBO waitCancelInfo = cancelApplyBService.getWaitCancelInfo(orderWork.getOrderId(), orderWork.getWorkId());
		if (Objects.equals(waitCancelInfo.getUserWaitCancelStatus(), GlobalConsts.YES)) {
			saasOrderDetailDRO.setWaitCancel(waitCancelInfo.getUserWaitCancelStatus());
			saasOrderDetailDRO.setCancelTime(waitCancelInfo.getCanelApplyTime());
		}else {
			// 查询跟单，是否已取消
			OrderWorkTrack orderWorkTrack = workTrackBService.getUserWaitCancelTrack(orderWork);
			if (orderWorkTrack != null) {
				saasOrderDetailDRO.setWaitCancel(GlobalConsts.YES);
				saasOrderDetailDRO.setCancelTime(orderWorkTrack.getCreateTime());
			}
		}
	}

	private void orderDetailSet(SaasOrderDetailDRO weixinOrderDetail, OrderDetail orderDetail) {
		weixinOrderDetail.setUserName(orderDetail.getUserName());
		weixinOrderDetail.setUserPhone(orderDetail.getTelephone());
		weixinOrderDetail.setProvinceId(orderDetail.getProvinceId());
		weixinOrderDetail.setProvinceName(orderDetail.getProvinceName());
		weixinOrderDetail.setCityName(orderDetail.getProvinceName());
		weixinOrderDetail.setCountryId(orderDetail.getCountyId());
		weixinOrderDetail.setCountryName(orderDetail.getCountyName());
		weixinOrderDetail.setStreetId(orderDetail.getStreetId());
		weixinOrderDetail.setStreet(orderDetail.getStreet());
		weixinOrderDetail.setAddress(orderDetail.getAddress());
		weixinOrderDetail.setRemark(orderDetail.getRemark());
	}

	private void refundSet(SaasOrderDetailDRO saasOrderDetailDRO,OrderWork orderWork) {
		// 存在退款单
		if (NumberUtil.isNotNullOrZero(orderWork.getRefundTargetWorkId())) {
			// 原单退款单 进行补全数据
			OrderWorkQuery query = new OrderWorkQuery();
			query.setOrderId(orderWork.getOrderId());
			query.setWorkType(Arrays.asList(OrderConsts.ORDER_TYPE_REFUND));
			query.setOrderField("receiveTime");
			List<EsOrderWork> refundWorks = orderWorkListBService.listPageOrderWorkByQuery(query);
			if (CollectionUtil.isNotNullOrEmpty(refundWorks)) {
				EsOrderWork esOrderWork = refundWorks.get(0);
				Integer refundAmount = refundWorks.stream().filter(e -> e.getRefundAmount() != null).mapToInt(e -> e.getRefundAmount()).sum();
				saasOrderDetailDRO.setRefundTime(esOrderWork.getLastRefundAmountTime());
				saasOrderDetailDRO.setRefundAmount(refundAmount);
				saasOrderDetailDRO.setRefundStatus(esOrderWork.getPayStatus());
				saasOrderDetailDRO.setCompleteRefundStatus(GlobalConsts.YES);
				saasOrderDetailDRO.setRefundOrderCount(refundWorks.size());
				saasOrderDetailDRO.setLastRefundAmount(esOrderWork.getRefundAmount());
			} else {
				saasOrderDetailDRO.setRefundOrderCount(GlobalConsts.NONE);
			}
		} else {
			saasOrderDetailDRO.setRefundTime(orderWork.getRefundTime());
			saasOrderDetailDRO.setCompleteRefundStatus(this.completeRefundStatus(orderWork));
			saasOrderDetailDRO.setRefundStatus(OrderConsts.getUserRefundStatus(NumberUtil.isNotNullOrZero(orderWork.getRefundTargetWorkId()), orderWork.getRefundReviewStatus(), orderWork.getPayStatus()));
		}
	}


	/**
	 * 处理完成前退款标示 （申请退款和退款完成都属于 完成前退款）
	 *
	 * @return
	 */
	private Integer completeRefundStatus(OrderWork orderWork) {
		// 审核中，退款中
		if (Objects.equals(orderWork.getRefundReviewStatus(), OrderConsts.REVIEW_STATUS_DOING)) {
			return GlobalConsts.NO;
		}

		// 退款成功
		if (Objects.equals(orderWork.getRefundReviewStatus(), OrderConsts.REVIEW_STATUS_SUCCESS)) {
			return GlobalConsts.NO;
		}

		if (Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getPrepayAmount())) {
			if (orderWork.getRefundTime() != null) {
				return GlobalConsts.NO;
			}
		}

		return GlobalConsts.NONE;
	}

	/**
	 * 获取实付金额
	 * @param orderWork
	 * @return
	 */
	private Integer factAmount(OrderWork orderWork) {
		Integer factAmount= getDepositAmount(orderWork);

		if (Objects.equals(orderWork.getMasterPayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getMasterAmount())) {
			factAmount = Optional.ofNullable(factAmount).orElse(0) + orderWork.getMasterAmount();
		}
		return factAmount;
	}

	/**
	 * 获取已付定金
	 *
	 * @param orderWork
	 * @return
	 */
	private Integer getDepositAmount(OrderWork orderWork) {
		Integer depositAmount = null;
		if (Objects.equals(orderWork.getChannelPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getChannelPrepayAmount())) {
			depositAmount = Optional.ofNullable(depositAmount).orElse(0) + orderWork.getChannelPrepayAmount();
		}
		if (Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getPrepayAmount())) {
			depositAmount = Optional.ofNullable(depositAmount).orElse(0) + orderWork.getPrepayAmount();
		}
		if (Objects.equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getDepositAmount())) {
			depositAmount = Optional.ofNullable(depositAmount).orElse(0) + orderWork.getDepositAmount();
		}
		return depositAmount;
	}

	/**
	 * 待支付
	 *
	 * @param orderWork
	 * @return
	 */
	private Integer getWaitPayAmount(OrderWork orderWork, SaasOrderDetailDRO saasOrderDetailDRO) {
		Integer waitPayAmount = null;
		// 取消状态
		List<Integer> resultStatusList = Lists.newArrayList(OrderStatusConsts.WORK_RESULT_FAIL, OrderStatusConsts.WORK_RESULT_DISCARD);
		// 未取消/失败
		boolean resultStatusSupport = !resultStatusList.contains(orderWork.getResultStatus());
		// 未完成
		boolean isComplete = orderWork.getCompleteTime() == null;
		// 未取消 未完成 待支付
		if (Objects.equals(PayConsts.PAY_STATUS_ING, orderWork.getPrepayStatus()) && resultStatusSupport && isComplete) {
			waitPayAmount = orderWork.getPrepayAmount();
			return waitPayAmount;
		}

		// 定金未支付
		if (!NumberUtil.isNullOrZero(orderWork.getDepositAmount()) && Objects.equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_NONE) && orderWork.getDepositTime() == null) {
			waitPayAmount = Optional.ofNullable(waitPayAmount).orElse(0) + orderWork.getDepositAmount();
		}
		// 师傅收款额度
		if (!Objects.equals(orderWork.getMasterPayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getMasterAmount())) {
			waitPayAmount = Optional.ofNullable(waitPayAmount).orElse(0) + orderWork.getMasterAmount();
		}
		return waitPayAmount;
	}
}
